<template>
  <div class="character-create">
    <el-form 
      :model="formData" 
      :rules="rules" 
      ref="formRef" 
      label-width="120px"
      label-position="top"
    >
      <!-- 角色名称 -->
      <el-form-item label="角色名称" prop="name">
        <el-input 
          v-model="formData.name" 
          placeholder="请输入角色名称（最多100字符）"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <!-- 角色图片上传 -->
      <el-form-item label="角色形象" prop="image_file">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-change="handleImageChange"
          :auto-upload="false"
        >
          <img v-if="previewImage" :src="previewImage" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">
          支持JPG/PNG格式，大小不超过5MB
          <el-link 
            type="primary" 
            @click="clearImage" 
            v-if="previewImage"
          >
            清除图片
          </el-link>
        </div>
      </el-form-item>

      <!-- 角色描述 -->
      <el-form-item label="角色描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入角色简要描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 背景故事 -->
      <el-form-item label="背景故事" prop="background">
        <el-input
          v-model="formData.background"
          type="textarea"
          :rows="5"
          placeholder="详细描述角色的背景故事"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>

      <!-- 喜好与特长 -->
      <el-form-item label="喜好与特长">
        <div class="json-input">
          <div v-for="(item, index) in preferencesItems" :key="index" class="item-row">
            <el-input v-model="item.key" placeholder="喜好或特长名称" class="key-input" />
            <el-input v-model="item.value" placeholder="具体描述" class="value-input" />
            <el-button type="danger" :icon="Close" circle @click="removePreference(index)" />
          </div>
          <el-button type="primary" :icon="Plus" text @click="addPreference">
            添加喜好或特长项
          </el-button>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button 
          type="primary" 
          @click="submitForm" 
          :loading="loading"
        >
          立即创建
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import { characterAPI } from '@/api/characters'
import { uploadAPI } from '@/api/upload'

// 表单数据
const formData = reactive({
  name: '',
  image_file: null, // 存储文件对象
  description: '',
  background: '',
  preferences: {}
})

const previewImage = ref('') // 本地预览图
const loading = ref(false)
const formRef = ref()

// 动态键值对数据
const preferencesItems = ref([])

// 监听喜好数据变化
watch(preferencesItems, (newItems) => {
  formData.preferences = newItems.reduce((acc, item) => {
    if (item.key) acc[item.key] = item.value
    return acc
  }, {})
}, { deep: true })

// 验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { max: 100, message: '名称长度不能超过100个字符', trigger: 'blur' }
  ],
  image_file: [
    { 
      validator: (rule, value, callback) => {
        if (!value) callback(new Error('请上传角色图片'))
        else callback()
      },
      trigger: 'change' 
    }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { max: 500, message: '描述长度不能超过500个字符', trigger: 'blur' }
  ],
  background: [
    { required: true, message: '请输入背景故事', trigger: 'blur' },
    { max: 2000, message: '背景故事长度不能超过2000个字符', trigger: 'blur' }
  ]
})

// 图片处理逻辑
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

const handleImageChange = (file) => {
  if (!file.raw) return

  // 生成预览图并保存文件对象
  previewImage.value = URL.createObjectURL(file.raw)
  formData.image_file = file.raw

  // 清理旧URL内存
  if (formData.image_url) {
    URL.revokeObjectURL(formData.image_url)
    formData.image_url = ''
  }
}

const clearImage = () => {
  formData.image_file = null
  previewImage.value = ''
  URL.revokeObjectURL(previewImage.value)
}

// 表单提交
const submitForm = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    loading.value = true

    // 1. 上传图片
    const imageData = await uploadAPI.uploadCharacter(formData.image_file)
    // 2. 创建角色
    const payload = {
      name: formData.name,
      image_url: imageData.url,
      description: formData.description,
      background: formData.background,
      preferences: formData.preferences,
      extra_info: formData.extra_info || null
    };
    delete payload.image_file // 移除临时文件对象

    const { data } = await characterAPI.createCharacter(payload)
    
    ElMessage.success({
      message: `角色创建成功！`,
      duration: 3000
    })
    resetForm()

  } catch (error) {
    handleSubmitError(error)
  } finally {
    loading.value = false
  }
}

// 错误处理
const handleSubmitError = (error) => {
  let message = error.message
  console.error('提交失败:', error)

  // 处理特定错误状态码
  if (error.response) {
    switch (error.response.status) {
      case 413:
        message = '图片文件过大，请压缩后重新上传'
        break
      case 415:
        message = '不支持的图片格式'
        break
      case 401:
        message = '登录已过期，请重新登录'
        break
      default:
        message = error.response.data?.message || `服务器错误：${error.response.status}`
    }
  }

  ElMessage.error(message)

  // 自动滚动到第一个错误字段
  const firstError = document.querySelector('.is-error')
  if (firstError) {
    firstError.scrollIntoView({ 
      behavior: 'smooth', 
      block: 'center' 
    })
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  clearImage()
  preferencesItems.value = []
  formData.preferences = {}
}

// 喜好项操作
const addPreference = () => preferencesItems.value.push({ key: '', value: '' })
const removePreference = (index) => preferencesItems.value.splice(index, 1)
</script>

<style scoped>
.character-create {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  text-align: center;
  line-height: 200px;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

.json-input {
  width: 100%;
}

.item-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.key-input {
  width: 200px;
}

.value-input {
  flex: 1;
}
</style>